<?php

namespace app\admin\controller;

use app\common\controller\Backend;

/**
 * 供应商管理
 *
 * @icon fa fa-circle-o
 */
class Supplier extends Backend
{

    /**
     * Supplier模型对象
     * @var \app\admin\model\Supplier
     */
    protected $model = null;

    /**
     * 原料模型对象
     * @var \app\admin\model\ClothmakingRaw
     */
    protected $clothmakingRaw = null;

    /**
     * 包材模型对象
     * @var \app\admin\model\PackageMaterial
     */
    protected $packageMaterial = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Supplier;
        $this->clothmakingRaw = new \app\admin\model\ClothmakingRaw;
        $this->packageMaterial = new \app\admin\model\PackageMaterial;
        $this->view->assign("supplyTypeList", $this->model->getSupplyTypeList());
    }

    /**
     * 供应商列表页
     * 
     * @return mixed
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $this->request->filter(['strip_tags']);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = $this->appendGoodsName($list);

            return json(['total' => $total, 'rows' => $list]);
        }

        return $this->view->fetch();
    }
    /**
     * 编辑供应商, 可以接收多个原料id
     * @return mixed
     * 编辑供应商信息（直接处理逗号分隔的ID字符串）
     */
    public function edit($ids = null)
    {
        $row = $this->model::get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");
            $row->name = $params['name'];
            $row->goods_id = $params['id'];
            $row->supply_type = $params['supply_type'];
            $row->delivery_time = $params['delivery_time'];
            $row->linkman = $params['linkman'];
            $row->contact = $params['contact'];
            $row->address = $params['address'];
            $row->remark = $params['remark'];
            $result = $row->save();
            if ($result === false) {
                $this->error($row->getError());
            }
            $this->success();
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 获取材料信息
     * @return \think\Response
     */
    public function getMaterialInfo()
    {
        $params = $this->request->post();
        $response = ['total' => 0, 'rows' => []];
        if (empty($params['searchKey'])) {
            $type = $params['type'];
            $data = $this->getMaterialByType($type);
            $response['total'] = count($data);
            $response['rows'] = $data;
            return json($response);
        } else {
            $data = $this->model::find($params['searchValue']);
            if ($data) {
                $goodsIds = explode(',', $data['goods_id']); // 分割商品ID

                // 根据供应类型查询详细信息
                if ($data['supply_type'] == '原料') {
                    $goodsData = $this->clothmakingRaw
                        ->where('id', 'in', $goodsIds)
                        ->field('id,name')
                        ->select();
                } else {
                    $goodsData = $this->packageMaterial
                        ->where('id', 'in', $goodsIds)
                        ->field('id,name')
                        ->select();
                }

                $response['rows'] = $goodsData;
                $response['total'] = count($goodsData);
            }
        }

        return json($response);
    }

    /**
     * 根据类型获取供应商信息
     * @param string $type 类型（0:原料, 1:包材）
     * @return \think\Response
     */
    public function getSupplierInfo()
    {
        $params = $this->request->post();
        $type = $this->convertTypeToText($params['type']);
        if (isset($params['searchKey'])){
            $data = $this->model->where('id', $params['keyValue'])->find();
            return json([
                'total' => 1,
                'rows' => $data
            ]);
        }

        $data = $this->model::where('supply_type', $type)->select();

        return json([
            'total' => count($data),
            'rows' => $data
        ]);
    }

    /**
     * 根据类型获取材料信息
     * @param string $type 类型（0:原料, 1:包材）
     * @return array
     */
    protected function getMaterialByType($type)
    {
        return $type == '0' ?
            $this->clothmakingRaw::select() :
            $this->packageMaterial::select();
    }

    /**
     * 根据供应商id获取材料信息
     * @param string $searchValue 搜索值
     * @return array|null
     */
    public function getMaterialBySearch($searchValue)
    {
        $data = $this->model::find($searchValue);
        if (!$data) {
            return null;
        }

        return $data["supply_type"] == "原料" ?
            $this->clothmakingRaw::find($data["goods_id"]) :
            $this->packageMaterial::find($data["goods_id"]);
    }

    /**
     * 转换类型为文本
     * @param string $type 类型（0:原料, 1:包材）
     * @return string
     */
    protected function convertTypeToText($type)
    {
        return $type == '0' ? '原料' : '包材';
    }

    /**
     * 为列表数据添加商品名称
     * @param array $list 列表数据
     * @return array
     */
    protected function appendGoodsName($list)
    {
        foreach ($list as &$item) {
            $goodsId = $item['goods_id'];
            $goodsName = '';

            if ($item['supply_type'] == '原料') {
                $goodsInfo = $this->clothmakingRaw->where('id', $goodsId)->find();
                $goodsName = $goodsInfo ? $goodsInfo['name'] : '未知原料';
            } elseif ($item['supply_type'] == '包材') {
                $goodsInfo = $this->packageMaterial->where('id', $goodsId)->find();
                $goodsName = $goodsInfo ? $goodsInfo['name'] : '未知包材';
            }

            $item['goods_name'] = $goodsName;
        }
        unset($item);

        return $list;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
